//
//  IncomeViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/8/5.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "IncomeTreeModel.h"
#import "PPIncomeTreeCell.h"

#import "IncomeViewController.h"
#import "ApprenticeListViewController.h"

@interface IncomeViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property (strong, nonatomic) IncomeTreeModel *treeModel;

@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation IncomeViewController

#pragma mark - life cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initView];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    [self openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
        
        if (isLogin) {
            [self request_InComeTree];
        }
    }];
}

#pragma mark 收益树
- (void)request_InComeTree {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@"1" forKey:@"curPage"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_POPULARIZE_INCOME_TREE];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    self.treeModel.bounty = [[resultDic valueForKey:@"bounty"] doubleValue];
                    
                    NSArray *rewardRes = [resultDic valueForKey:@"rewardRes"];

                    [self.treeModel.incomeItemListArray removeAllObjects];
                    
                    for (int i = 0; i < rewardRes.count; i++) {
                        
                        NSDictionary *incomeDic = [rewardRes objectAtIndex:i];
                        IncomeItemModel *model = [[IncomeItemModel alloc] init];
                        model.incomeCount = [[incomeDic valueForKey:@"acquirableMoney"] stringValue];
                        model.incomeID = [incomeDic valueForKey:@"id"];
                        model.isCollect = [[incomeDic valueForKey:@"canExtracted"] boolValue];
                        NSString *rewardType = [incomeDic valueForKey:@"rewardType"];
                        if (![rewardType isKindOfClass:[NSString class]]) {
                            rewardType = [NSString stringWithFormat:@"%@",rewardType];
                        }
                        
                        if ([rewardType isEqualToString:@"1"]) {
                            model.incomeType = ETTIncomeType_Coin;
                            model.radius = 1;
                        } else if ([rewardType isEqualToString:@"2"]){
                            model.incomeType = ETTIncomeType_RedPaper;
                            model.radius = 0.75;
                        } else {
                            model.incomeType = ETTIncomeType_Coin;
                            model.radius = 1;
                        }                        
                        [self.treeModel.incomeItemListArray addObject:model];
                    }
                }
                
                [[TTNoResultManager shareManager] hideNoResultWithView:self.view];
            } else {
                
                //检查到未登录
                if ([code isEqualToString:@"401"]) {
                    
                    [[TTUserModel sharedObject] initialization];
                    
                    [self openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
                        if (isLogin) {
                            [self request_InComeTree];
                        }
                    }];
                    
                } else {
                    
                    [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                    [SVProgressHUD dismissWithDelay:1];
                    [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:kTTViewStateNoData btnTitle:@"重新加载" didPressButton:^{
                        [self request_InComeTree];
                    }];
                }
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
            
        } else {
            
        }
        
        [self.tableview reloadData];
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_InComeTree];
        }];
    }];
}

#pragma mark 收取收益
- (void)requestExtractWithIndex:(NSInteger)index {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.treeModel.incomeItemListArray[index].incomeID forKey:@"id"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_POPULARIZE_INCOME_EXTRACT];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {

                }
                
            } else {

                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }

        } else {

        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}

#pragma mark 一键收取
- (void)request_AllIncome {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_POPULARIZE_INCOME_EXTRACTALL];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                [Utilities playSoundWithFileName:@"allCoin" fileType:@"wav"];
                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:0.5];
                
            } else {
                
                [self alert:[data valueForKey:@"msg"]];
            }
            
            [self request_InComeTree];
            
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)initView {
    
    self.title = @"收益";
    
    self.tableview.scrollEnabled = NO;
    [self.tableview registerClass:[PPIncomeTreeCell class] forCellReuseIdentifier:@"PPIncomeTreeCellID"];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPIncomeTreeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PPIncomeTreeCellID" forIndexPath:indexPath];
    
    [cell fillCellWithArray:self.treeModel.incomeItemListArray AndBounty:self.treeModel.bounty];
    
    WEAKSELF
    cell.incomeCollectBlock = ^(NSInteger index) {
        
        [weakSelf requestExtractWithIndex:index];
    };
    
    //收益全部收取完毕
    cell.incomeCollectFinishBlock = ^{
        
        [weakSelf.treeModel.incomeItemListArray removeAllObjects];
        [weakSelf request_InComeTree];
    };
    
    //收取所有可收取收益
    cell.incomeCollectAllBlock = ^{
        
        [weakSelf  request_AllIncome];
    };
    
    //去师徒
    cell.goApprenticeListBlock = ^{
        ApprenticeListViewController *VC = [[ApprenticeListViewController alloc] init];
        [weakSelf.navigationController pushViewController:VC animated:YES];
    };
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return TTScreenHeight - kNavBarAndStatusBarHeight - kTabBarHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    ApprenticeListViewController *VC = [[ApprenticeListViewController alloc] init];
//    [self.navigationController pushViewController:VC animated:YES];
}

- (IncomeTreeModel *)treeModel {
    if (!_treeModel) {
        _treeModel = [[IncomeTreeModel alloc] init];
        _treeModel.incomeItemListArray = @[].mutableCopy;
    }
    return _treeModel;
}
@end
